package com.xuesinuo.ots.config.i18n;

import org.springframework.stereotype.Component;

import com.xuesinuo.ots.util.StringUtil;
import com.xuesinuo.xtool.Np;

import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;

@Component
@RequiredArgsConstructor
public class I18nToolImpl implements I18nTool {

    private final HttpServletRequest request;

    @Override
    public I18nLanguage getLanguage() {
        String languageCode = null;

        try {
            if (StringUtil.isBlank(languageCode)) {
                languageCode = Np.i(request).x(x -> x.getHeader("Content-Language")).o();
            }
            if (StringUtil.isBlank(languageCode)) {
                languageCode = Np.i(request).x(x -> x.getHeader("APP-LANGUAGE")).o();
            }
        } catch (Exception e) {}

        return I18nLanguage.getByCode(languageCode);
    }

    @Override
    public I18nLanguage getLanguageAsDefault() {
        I18nLanguage result = this.getLanguage();
        return result == null ? I18nLanguage.CN : result;
    }

    @Override
    public String getTip(I18nTips i18nTips, Object... args) {
        if (i18nTips == null) {
            return "";
        }
        I18nLanguage lang = this.getLanguageAsDefault();
        return i18nTips.getTip(lang, args);
    }
}